import store from '@/store'
import dayjs from 'dayjs'
import context from '@/main'
import define from '@/utils/define'
const STORAGEPREFIX = 'jsbos_'
const STORAGETYPE = window.localStorage

const jsbos = {
  toDateText(dateTimeStamp) {
    let result = ''
    let minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
    let hour = minute * 60;
    let day = hour * 24;
    let week = day * 7;
    let halfamonth = day * 15;
    let month = day * 30;
    let now = new Date().getTime(); //获取当前时间毫秒
    let diffValue = now - dateTimeStamp; //时间差
    if (diffValue < 0) return "刚刚"
    let minC = diffValue / minute; //计算时间差的分，时，天，周，月
    let hourC = diffValue / hour;
    let dayC = diffValue / day;
    let weekC = diffValue / week;
    let monthC = diffValue / month;
    if (monthC >= 1 && monthC <= 3) {
      result = " " + parseInt(monthC) + "月前"
    } else if (weekC >= 1 && weekC <= 3) {
      result = " " + parseInt(weekC) + "周前"
    } else if (dayC >= 1 && dayC <= 6) {
      result = " " + parseInt(dayC) + "天前"
    } else if (hourC >= 1 && hourC <= 23) {
      result = " " + parseInt(hourC) + "小时前"
    } else if (minC >= 1 && minC <= 59) {
      result = " " + parseInt(minC) + "分钟前"
    } else if (diffValue >= 0 && diffValue <= minute) {
      result = "刚刚"
    } else {
      let datetime = new Date();
      datetime.setTime(dateTimeStamp);
      let Nyear = datetime.getFullYear();
      let Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
      let Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
      let Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
      let Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
      let Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
      result = Nyear + "-" + Nmonth + "-" + Ndate
    }
    return result;
  },
  getDate(format, strInterval, number) {
    var myDate = new Date();
    var dtTmp = new Date();
    if (!!strInterval) {
      switch (strInterval) {
        case 's':
          myDate = new Date(Date.parse(dtTmp) + (1000 * number)); // 秒
          break;
        case 'n':
          myDate = new Date(Date.parse(dtTmp) + (60000 * number)); // 分
          break;
        case 'h':
          myDate = new Date(Date.parse(dtTmp) + (3600000 * number)); // 小时
          break;
        case 'd':
          myDate = new Date(Date.parse(dtTmp) + (86400000 * number)); // 天
          break;
        case 'w':
          myDate = new Date(Date.parse(dtTmp) + ((86400000 * 7) * number)); // 星期
          break;
        case 'q':
          myDate = new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds()); // 季度
          break;
        case 'm':
          myDate = new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds()); // 月
          break;
        case 'y':
          myDate = new Date((dtTmp.getFullYear() + number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds()); // 年
          break;
        default:
      }
    }
    return jsbos.toDate(myDate, format);
  },
  toDate(v, format) {
    format = format ? format : "yyyy-MM-dd HH:mm"
    if (!v) return "";
    var d = v;
    if (typeof v === 'string') {
      if (v.indexOf("/Date(") > -1)
        d = new Date(parseInt(v.replace("/Date(", "").replace(")/", ""), 10));
      else
        d = new Date(Date.parse(v.replace(/-/g, "/").replace("T", " ").split(".")[0]));
    } else {
      d = new Date(v)
    }
    var o = {
      "M+": d.getMonth() + 1,
      "d+": d.getDate(),
      "h+": d.getHours(),
      "H+": d.getHours(),
      "m+": d.getMinutes(),
      "s+": d.getSeconds(),
      "q+": Math.floor((d.getMonth() + 3) / 3),
      "S": d.getMilliseconds()
    };
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
      }
    }
    return format;
  },
  getThatDay(space) {
    if (space == undefined) {
      space = 0
    }

    let date = new Date()
    date.setTime(date.getTime() + 86400000 * space)
    return this.assemblyDay({
      year: date.getFullYear(),
      month: date.getMonth(),
      date: date.getDate()
    })
  },
  assemblyDay(data) {
    let year = data.year.toString()
    data.month = Number(data.month + 1)
    let month = this.complement(data.month)
    let date = this.complement(data.date)
    return year + '-' + month + '-' + date
  },
  complement(value, digit) {
    digit = digit ? digit : 2
    value = Number(value)
    if (value < Math.pow(10, digit - 1)) {
      let text = ''
      for (let i = 0; i < digit - value.toString().length; i++) {
        text = text + '0'
      }
      return text + value
    } else {
      return value.toString()
    }
  },
  toTreeViewJson(data, id, parentIdText, idText) {
    parentIdText = parentIdText ? parentIdText : 'parentId'
    idText = idText ? idText : 'id'
    id = id ? id : 0
    let treeJson = [];
    let childNode = data.filter(v => v[parentIdText] == id);
    if (childNode.length > 0) {
      for (let i = 0; i < childNode.length; i++) {
        let treeModel = {
          ...childNode[i],
          hasChildren: !!data.filter(v => v[parentIdText] == childNode[i][idText]).length,
          ChildNodes: jsbos.toTreeViewJson(data, childNode[i][idText], parentIdText, idText),
          isexpand: childNode[i].isexpand == undefined ? true : childNode[i].isexpand,
          complete: true,
        }
        treeJson.push(treeModel);
      }
    }
    return treeJson;
  },
  toFileSize(size) {
    if (size == null || size == "") {
      return "";
    }
    if (size < 1024.00)
      return jsbos.toDecimal(size) + " 字节";
    else if (size >= 1024.00 && size < 1048576)
      return jsbos.toDecimal(size / 1024.00) + " KB";
    else if (size >= 1048576 && size < 1073741824)
      return jsbos.toDecimal(size / 1024.00 / 1024.00) + " MB";
    else if (size >= 1073741824)
      return jsbos.toDecimal(size / 1024.00 / 1024.00 / 1024.00) + " GB";
  },
  toDecimal(num) {
    if (num == null) {
      num = "0";
    }
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
      num = "0";
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    var cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
      cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
      num = num.substring(0, num.length - (4 * i + 3)) + '' +
        num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + '.' + cents);
  },
  toUrl(url) {
    return process.env.VUE_APP_BASE_API + url;
  },
  getAuth() {
    return store.getters.token;
  },
  idGenerator() {
    let quotient = (new Date() - new Date('2020-08-01'))
    quotient += Math.ceil(Math.random() * 1000)
    const chars = '0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz';
    const charArr = chars.split("")
    const radix = chars.length;
    const res = []
    do {
      let mod = quotient % radix;
      quotient = (quotient - mod) / radix;
      res.push(charArr[mod])
    } while (quotient);
    return res.join('')
  },
  getScriptFunc(str) {
    let func = null
    try {
      func = eval(str)
      return func
    } catch (error) {
      console.log(error);
      return false
    }
  },
  interfaceDataHandler(data) {
    if (!data.dataProcessing) return data.data
    const dataHandler = this.getScriptFunc(data.dataProcessing)
    if (!dataHandler) return data.data
    return dataHandler(data.data)
  },
  // 基于dayjs日期格式化,时间戳(毫秒)转日期
  dateFormat(date, format) {
    format = format || 'YYYY-MM-DD HH:mm'
    if (!date) return ''
    return dayjs(date).format(format)
  },
  // 基于dayjs日期格式化,时间戳(毫秒)转日期
  dateFormatDay(date, format) {
    format = format || 'YYYY-MM-DD'
    if (!date) return ''
    return dayjs(date).format(format)
  },
  dateFormatDayImportExcel(date, format) {
    format = format || 'YYYY/MM/DD'
    if (!date) return ''
    return dayjs(date).format(format)
  },
  // 基于dayjs日期格式化,日期转时间戳(毫秒)
  timestamp(val) {
    return dayjs(val).valueOf()
  },
  // 基于dayjs日期格式化, 表格专用
  tableDateFormat(row, column, cellValue) {
    let format = 'YYYY-MM-DD HH:mm'
    if (!cellValue) return ''
    return dayjs(cellValue).format(format)
  },
  tableDateFormats(row, column, cellValue) {
    let format = 'YYYY-MM-DD HH:mm:ss'
    if (!cellValue) return ''
    return dayjs(cellValue).format(format)
  },
  tableDayFormat(row, column, cellValue) {
    let format = 'YYYY-MM-DD'
    if (!cellValue) return ''
    return dayjs(cellValue).format(format)
  },
  storageSet(obj) {
    for (let i in obj) {
      cacheItem(i, obj[i])
    }

    function cacheItem(key, val) {
      key = STORAGEPREFIX + key
      let valType = typeof (val)
      if (val !== null) {
        var valConstructor = val.constructor
      }
      if (valType === 'string' || valType === 'number' || valType === 'boolean') {
        if (valConstructor === String) {
          val = val + '|String'
        } else if (valConstructor === Number) {
          val = val + '|Number'
        } else if (valConstructor === Boolean) {
          val = val + '|Boolean'
        }
        STORAGETYPE.setItem(key, val)
      } else if (valType === 'object') {
        if (val === null) {
          val = JSON.stringify(val) + '|Null'
          STORAGETYPE.setItem(key, val)
        } else {
          if (valConstructor === Array) {
            val = JSON.stringify(val) + '|Array'
          } else if (valConstructor === Object) {
            val = JSON.stringify(val) + '|Object'
          }
          STORAGETYPE.setItem(key, val)
        }
      }
    }
  },
  storageGet(key) {
    key = STORAGEPREFIX + key
    let keyName = STORAGETYPE.getItem(key)
    if (keyName === null) {
      return null
    }
    let valArr = keyName.split('|')
    let getDataType = valArr[valArr.length - 1]
    valArr.splice(valArr.length - 1, 1)
    let val = valArr.join('')
    if (getDataType === 'Number') {
      val = parseInt(val)
    } else if (getDataType === 'Boolean') {
      if (val === 'true') {
        val = true
      } else {
        val = false
      }
    } else if (getDataType === 'Array' || getDataType === 'Object' || getDataType === 'Null') {
      val = JSON.parse(val)
    }
    return val
  },
  storageRemove(key) {
    STORAGETYPE.removeItem(STORAGEPREFIX + key)
  },
  storageClear() {
    for (let i in STORAGETYPE) {
      if (i.indexOf(STORAGEPREFIX) !== -1) {
        STORAGETYPE.removeItem(i)
      }
    }
  },
  hasP(enCode) {
    const permissionList = store.getters && store.getters.permissionList
    const modelId = context.$route.meta.modelId || ''
    if (!modelId) return false
    const list = permissionList.filter(o => o.modelId === modelId)
    if (!list.length) return false
    const columnList = list[0] && list[0].column ? list[0].column : []
    if (!columnList.length) return false
    const hasPermission = columnList.some(column => column.enCode === enCode)
    if (hasPermission) return true
    return false
  },
  hasFormP(enCode) {
    const permissionList = store.getters && store.getters.permissionList
    const modelId = context.$route.meta.modelId || ''
    if (!modelId) return false
    const list = permissionList.filter(o => o.modelId === modelId)
    if (!list.length) return false
    const formList = list[0] && list[0].form ? list[0].form : []
    if (!formList.length) return false
    const hasPermission = formList.some(form => form.enCode === enCode)
    if (hasPermission) return true
    return false
  },
  hasBtnP(enCode) {
    const permissionList = store.getters && store.getters.permissionList
    const modelId = context.$route.meta.modelId || ''
    if (!modelId) return false
    const list = permissionList.filter(o => o.modelId === modelId)
    if (!list.length) return false
    const btnList = list[0] && list[0].button ? list[0].button : []
    if (!btnList.length) return false
    const hasPermission = btnList.some(btn => btn.enCode === enCode)
    if (hasPermission) return true
    return false
  },
  downloadFile(url, name) {
    if (!url) return
    const baseUrl = url.indexOf('http') > -1 ? '' : define.comUrl
    const a = document.createElement('a')
    a.setAttribute('download', '')
    const realUrl = baseUrl + url + (name ? '&name=' + name : '')
    a.setAttribute('href', realUrl)
    a.click()
  },
  isEmpty(data) {
    return data === null || data === undefined || data === ''
  },
  isEmptyArray(data) {
    return Array.isArray(data) ? data.length === 0 : true
  },



  //金额转千分位
  // 可转正数，负数，小数
  toThousands(number) {
    if (!number) return;
    let arr = number.toString().split('')
    let numArr = [], pointStr = ''
    if (arr.indexOf('.') === -1) {  // 是否为小数
      numArr = arr.reverse()
    } else {
      numArr = arr.slice(0, arr.indexOf('.')).reverse()
      pointStr = arr.slice(arr.indexOf('.'), arr.length).join('')
    }
    let l = arr[0] == '-' ? numArr.length - 1 : numArr.length
    let symbolStr = arr[0] == '-' ? arr[0] : ''  // 是否为负数
    let numStr = ''
    for (let i = 0; i < l; i++) {
      if (i != 0 && i % 3 === 0) {
        numStr = numArr[i] + ',' + numStr
      } else {
        numStr = numArr[i] + numStr
      }
    }
    return symbolStr + numStr + pointStr
  },
  //金额千分位字符转数字
  changeNumber(val) {
    if (val) {
      let a = (val + "").replace(/,/g, "");
      return Number(a)
    } else {
      return 0
    }
  },
  // 检测两个数组中的值是否相等，不包含对象，仅限于基本数据类型
  arraysEqual(arr1, arr2) {
    if (arr1.length !== arr2.length) return false;
    for (var i = 0; i < arr1.length; i++) {
      if (arr1[i] !== arr2[i]) return false;
    }
    return true;
  },
  //判断两个数组是否完全相同（数组里可以是数字 字符串 对象等）
  equalsObj(oldData, newData) {
    // 类型为基本类型时,如果相同,则返回true
    if (oldData === newData) return true;
    if (isObject(oldData) && isObject(newData) && Object.keys(oldData).length === Object.keys(newData).length) {
      // 类型为对象并且元素个数相同

      // 遍历所有对象中所有属性,判断元素是否相同
      for (const key in oldData) {
        if (oldData.hasOwnProperty(key)) {
          if (!equalsObj(oldData[key], newData[key]))
            // 对象中具有不相同属性 返回false
            return false;
        }
      }
    } else if (isArray(oldData) && isArray(oldData) && oldData.length === newData.length) {
      // 类型为数组并且数组长度相同

      for (let i = 0, length = oldData.length; i < length; i++) {
        if (!equalsObj(oldData[i], newData[i]))
          // 如果数组元素中具有不相同元素,返回false
          return false;
      }
    } else {
      // 其它类型,均返回false
      return false;
    }

    // 走到这里,说明数组或者对象中所有元素都相同,返回true
    return true;
  },



  //金额小写转换大写：
  menoyToUppercase(money) {
    var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');	 //汉字的数字
    var cnIntRadice = new Array('', '拾', '佰', '仟'); //基本单位
    var cnIntUnits = new Array('', '万', '亿', '兆');  //对应整数部分扩展单位
    var cnDecUnits = new Array('角', '分', '毫', '厘'); //对应小数部分单位
    var cnInteger = '整';	//整数金额时后面跟的字符
    var cnIntLast = '元';	//整数完以后的单位
    //最大处理的数字
    var maxNum = 999999999999999.9999;
    var integerNum;	 //金额整数部分
    var decimalNum;	 //金额小数部分
    //输出的中文金额字符串
    var chineseStr = '';
    var parts;		//分离金额后用的数组，预定义
    if (money == '') { return ''; }

    money = parseFloat(money);
    if (money >= maxNum) {
      //超出最大处理数字
      return '超出最大处理数字';
    }
    if (money == 0) {
      chineseStr = cnNums[0] + cnIntLast + cnInteger;
      return chineseStr;
    }
    //四舍五入保留两位小数,转换为字符串
    money = Math.round(money * 100).toString();
    integerNum = money.substr(0, money.length - 2);
    decimalNum = money.substr(money.length - 2);
    //获取整型部分转换
    if (parseInt(integerNum, 10) > 0) {
      var zeroCount = 0;
      var IntLen = integerNum.length;
      for (var i = 0; i < IntLen; i++) {
        var n = integerNum.substr(i, 1);
        var p = IntLen - i - 1;
        var q = p / 4;
        var m = p % 4;
        if (n == '0') {
          zeroCount++;
        } else {
          if (zeroCount > 0) {
            chineseStr += cnNums[0];
          }
          //归零
          zeroCount = 0;
          chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
        }
        if (m == 0 && zeroCount < 4) {
          chineseStr += cnIntUnits[q];
        }
      }
      chineseStr += cnIntLast;
    }
    //小数部分
    if (decimalNum != '') {
      var decLen = decimalNum.length;
      for (var i = 0; i < decLen; i++) {
        var n = decimalNum.substr(i, 1);
        if (n != '0') {
          chineseStr += cnNums[Number(n)] + cnDecUnits[i];
        }
      }
    }
    if (chineseStr == '') {
      chineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (decimalNum == '' || /^0*$/.test(decimalNum)) {
      chineseStr += cnInteger;
    }
    return chineseStr;
  },

  //检测当前form验证 是否通过，如果未通过将自动跳转为通过的地方
  moveToErr() {
    let isError = document.getElementsByClassName("is-error");
    if (isError.length) {
      isError[0].scrollIntoView({
        block: "center",
        behavior: "smooth",
      });
    }
  },



  checkSetting(data) {
    let Readonly = true;
    data.formOperates.forEach(item => {
      if (item.write) {
        Readonly = false
      }
    })
    data.readonly = Readonly;
    console.log('datadatadata', data)
    return data;
  }


  ,

  // 失去焦点金额格式化
  amountFormat(value) {
    if (!value || value == 0)
      return 0;
    let temp = Number(value) || null;
    // this.totalprice = this.priceFormat(temp);
    return jsbos.priceFormat(temp);
  },
  // 获得焦点金额去掉格式
  clearFormat(value) {
    if (!!value) {
      // this.totalprice = this.delcommafy(el.target.value);
      return jsbos.delcommafy(value);
    } else {
      totalprice = null;
    }
  },
  priceFormat(num, n) {
    n = n || 2;
    let symbol = ",";
    if (num === null) return num;
    if (typeof num !== "number")
      throw new TypeError("num参数应该是一个number类型");
    if (n < 0) throw new Error("参数n不应该小于0");
    let hasDot = parseInt(num) != num; //这里检测num是否为小数，true表示小数
    let m = n != undefined && n != null ? n : 1;
    num =
      m == 0
        ? num.toFixed(m) + "."
        : hasDot
          ? n
            ? num.toFixed(n)
            : num
          : num.toFixed(m);
    symbol = symbol || ",";
    num = num
      .toString()
      .replace(/(\d)(?=(\d{3})+\.)/g, function (match, p1, p2) {
        return p1 + symbol;
      });
    if (n == 0 || (!hasDot && !n)) {
      //如果n为0或者传入的num是整数并且没有指定整数的保留位数，则去掉前面操作中的小数位
      num = num.substring(0, num.indexOf("."));
    }
    return num;
  },
  //去除千分位中的‘，’
  delcommafy(num) {
    if (!num) return num;
    num = num.toString();
    num = num.replace(/,/gi, "");
    if (num.indexOf(".00") > 0) num = parseInt(num);
    return num;
  },
  dealBigMoney(n) {
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) return "数据非法";
    let unit = "千百拾亿千百拾万千百拾元角分",
      str = "";
    n += "00";
    let p = n.indexOf(".");
    if (p >= 0) {
      n = n.substring(0, p) + n.substr(p + 1, 2);
      unit = unit.substr(unit.length - n.length);
    }

    for (var i = 0; i < n.length; i++)
      str += "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) + unit.charAt(i);
    return str
      .replace(/零(千|百|拾|角)/g, "零")
      .replace(/(零)+/g, "零")
      .replace(/零(万|亿|元)/g, "$1")
      .replace(/(亿)万|壹(拾)/g, "$1$2")
      .replace(/^元零?|零分/g, "")
      .replace(/元$/g, "元整");
  }
}
export default jsbos
